/*
 * Copyright 2009 Phil Burk, Mobileer Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jsyn.examples;

import com.jsyn.JSyn;
import com.jsyn.Synthesizer;
import com.jsyn.unitgen.LineOut;
import com.jsyn.unitgen.SawtoothOscillator;
import com.jsyn.unitgen.SineOscillator;
import com.softsynth.shared.time.TimeStamp;

import java.util.List;

import static org.example.Main.generateTwelveToneEqualTemperament;
import static org.example.Main.playFrequency;

/**
 * Play notes using timestamped noteOn and noteOff methods of the UnitVoice.
 *
 * @author Phil Burk (C) 2009 Mobileer Inc
 */
public class PlayNotes {

    private void test() {

        // Create a context for the synthesizer.
        Synthesizer synth = JSyn.createSynthesizer();
        // Set output latency to 123 msec because this is not an interactive app.
        synth.getAudioDeviceManager().setSuggestedOutputLatency(0.123);

        // Add a tone generator.
        SawtoothOscillator voice = new SawtoothOscillator();
        synth.add(voice);
        // synth.add( ugen = new SineOscillator() );
        // synth.add( ugen = new SubtractiveSynthVoice() );
        // Add an output mixer.
        LineOut lineOut = new LineOut();
        synth.add(lineOut);

        // Connect the oscillator to the left and right audio output.
        voice.getOutput().connect(0, lineOut.input, 0);
        voice.getOutput().connect(0, lineOut.input, 1);

        // Start synthesizer using default stereo output at 44100 Hz.
        synth.start();

        // Get synthesizer time in seconds.
        double timeNow = synth.getCurrentTime();

        // Advance to a near future time so we have a clean start.
        TimeStamp timeStamp = new TimeStamp(timeNow + 0.5);

        // We only need to start the LineOut. It will pull data from the
        // oscillator.
        synth.startUnit(lineOut, timeStamp);

        // Schedule a note on and off.
        double freq = 200.0; // hertz
        double duration = 2;
        double onTime = 1;
        voice.noteOn(freq, 0.5, timeStamp);
        voice.noteOff(timeStamp.makeRelative(onTime));

        // Schedule this to happen a bit later.
        timeStamp = timeStamp.makeRelative(duration);
        freq *= 1.5; // up a perfect fifth
        voice.noteOn(freq, 0.5, timeStamp);
        voice.noteOff(timeStamp.makeRelative(onTime));

        timeStamp = timeStamp.makeRelative(duration);
        freq *= 4.0 / 5.0; // down a major third
        voice.noteOn(freq, 0.5, timeStamp);
        voice.noteOff(timeStamp.makeRelative(onTime));

        // Sleep while the song is being generated in the background thread.
        try {
            synth.sleepUntil(timeStamp.getTime() + 2.0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Stop everything.
        synth.stop();
    }

    private void playDoReMi() {
        // 创建合成器
        Synthesizer synth = JSyn.createSynthesizer();
        synth.getAudioDeviceManager().setSuggestedOutputLatency(0.123);

        // 添加模块
        SineOscillator voice = new SineOscillator();

        LineOut lineOut = new LineOut();
        synth.add(voice);
        synth.add(lineOut);

        // 连接音频模块
        voice.getOutput().connect(0, lineOut.input, 0);
        voice.getOutput().connect(0, lineOut.input, 1);

        // 启动合成器
        synth.start();
        TimeStamp timeStamp = new TimeStamp(synth.getCurrentTime() + 0.5);
        synth.startUnit(lineOut, timeStamp);

        // 定义 "C大调" 音符频率
        double[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88}; // do re mi fa so la si
        List<Double> twelveToneEqualTemperamentList = generateTwelveToneEqualTemperament(261.63,13);
        int[] majorScaleSteps = {-1, 0, 2, 4, 5, 7, 9, 11, 12}; // C大调音阶的半音位置
        double duration = 0.5; // 每个音符持续时间
        double amplitude = 0.1; // 音量

        // 播放音符序列
        for (double freq : twelveToneEqualTemperamentList) {
            timeStamp = playNote(voice, freq, amplitude, duration, timeStamp);
        }


//        List<Double> twelveToneEqualTemperamentList = generateTwelveToneEqualTemperament(261.63,13);
//
//        int[] majorScaleSteps = {-1, 0, 2, 4, 5, 7, 9, 11, 12}; // C大调音阶的半音位置
//        int quarter = 1;
//        int volume = 1;
//        timeStamp = playNote(voice, twelveToneEqualTemperamentList.get(3),volume,quarter,timeStamp); //我
//        timeStamp = playNote(voice, twelveToneEqualTemperamentList.get(3),volume,quarter,timeStamp); //想
//        timeStamp = playNote(voice, twelveToneEqualTemperamentList.get(3),volume,quarter,timeStamp); //你
//        timeStamp = playNote(voice, twelveToneEqualTemperamentList.get(3),volume,quarter,timeStamp); //已
//        timeStamp = playNote(voice, twelveToneEqualTemperamentList.get(2),volume,quarter/2,timeStamp);//表
//        timeStamp = playNote(voice, twelveToneEqualTemperamentList.get(1),volume,quarter/2,timeStamp);//表
//        timeStamp = playNote(voice, twelveToneEqualTemperamentList.get(1),volume,quarter,timeStamp);//现

        // 等待播放完成
        try {
            synth.sleepUntil(timeStamp.getTime() + 1.0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 停止合成器
        synth.stop();
    }

    /**
     * 播放单个音符
     *
     * @param voice      振荡器
     * @param freq       音符频率 (Hz)
     * @param amplitude  音量大小 (0.0 - 1.0)
     * @param duration   音符持续时间 (秒)
     * @param timeStamp  当前时间戳
     * @return 下一个时间戳
     */
    private TimeStamp playNote(SineOscillator voice, double freq, double amplitude, double duration, TimeStamp timeStamp) {
        // 播放音符
        voice.noteOn(freq, amplitude, timeStamp);
        // 关闭音符
        voice.noteOff(timeStamp.makeRelative(duration));
        // 返回下一个音符的时间戳
        return timeStamp.makeRelative(duration);
    }

    public static void main(String[] args) {
        new PlayNotes().playDoReMi();
    }
}
